using System;
using System.Reflection;

public class ReflectionAction : QueuableAction
{
	public struct ActionBuilderParams
	{
		public object actionObject;

		public string typeName;

		public string runMethodName;

		public object[] runMethodParams;

		public string stopMethodName;

		public object[] stopMethodParams;
	}

	private ActionBuilderParams builderParams;

	public ReflectionAction(ActionBuilderParams builderParams)
	{
		this.builderParams = builderParams;
		if (!AreParametersValid(builderParams))
		{
			throw new ArgumentException("Invalid builderParams");
		}
	}

	private bool AreParametersValid(ActionBuilderParams builderParams)
	{
		MethodInfo methodInfo = GetMethodInfo(builderParams.runMethodName);
		ParameterInfo[] parameterInfo = GetParameterInfo(methodInfo);
		if (parameterInfo.Length < 1)
		{
			return false;
		}
		return parameterInfo[parameterInfo.Length - 1].ParameterType == typeof(OnComplete);
	}

	private MethodInfo GetMethodInfo(string methodName)
	{
		Type myType = GetMyType();
		return myType.GetMethod(methodName);
	}

	private Type GetMyType()
	{
		if (builderParams.actionObject == null)
		{
			return Type.GetType(builderParams.typeName);
		}
		return builderParams.actionObject.GetType();
	}

	private ParameterInfo[] GetParameterInfo(MethodInfo methodInfo)
	{
		return methodInfo.GetParameters();
	}

	public override void DoStart(OnComplete onComplete)
	{
		object[] wrapperParams = GetWrapperParams(onComplete);
		MethodInfo methodInfo = GetMethodInfo(builderParams.runMethodName);
		methodInfo.Invoke(builderParams.actionObject, wrapperParams);
	}

	private object[] GetWrapperParams(OnComplete onComplete)
	{
		object[] array = new object[builderParams.runMethodParams.Length];
		builderParams.runMethodParams.CopyTo(array, 0);
		array[array.Length - 1] = onComplete;
		return array;
	}

	public override void Stop()
	{
		MethodInfo methodInfo = GetMethodInfo(builderParams.stopMethodName);
		methodInfo.Invoke(builderParams.actionObject, builderParams.stopMethodParams);
	}

	public override void OnDone()
	{
		object obj = builderParams.runMethodParams[builderParams.runMethodParams.Length - 1];
		if (obj != null && obj.GetType() == typeof(OnComplete))
		{
			OnComplete onComplete = obj as OnComplete;
			onComplete();
		}
	}
}
